/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package simplepushserver.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.StringTokenizer;

/**
 *
 * @author Filip
 */
public class ZippyParser {

    public static String parseToLink(String url) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(new URL(url).openStream()));
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();
        sb.append(line);
        while (line != null) {
            line = br.readLine();
            sb.append(line);
        }
        line = sb.toString();
        int dlStart = line.indexOf("document.getElementById('dlbutton').href = ") + "document.getElementById('dlbutton').href = ".length();
        int dlEnd = line.indexOf(';',dlStart);
        line = line.substring(dlStart, dlEnd);
        String firstPart = line.substring(line.indexOf("\""));
        int firstPar =  firstPart.indexOf('(')+1;
        int lastPar =  firstPart.indexOf(')');
        String tricky = line.substring(firstPar,lastPar);
        tricky = tricky.replace("%", " % ");
        StringTokenizer st= new StringTokenizer(tricky);
        int first = Integer.parseInt(st.nextToken());
        st.nextToken();
        first = first % Integer.parseInt(st.nextToken());
        st.nextToken();
        int last = Integer.parseInt(st.nextToken());
        st.nextToken();
        last = last % Integer.parseInt(st.nextToken());
        int ans = first + last;
        
        String res = url.substring(0, url.indexOf(".com/")+4);
        res += firstPart.substring(1, firstPar-3);
        res += ans;
        res += firstPart.substring(lastPar+3,firstPart.length()-1);
        return res;

        //document.getElementById('dlbutton').href = "/d/16607190/"+(278826%51245 + 278826%913)+"/Deadmau5%20-%20A%20City%20In%20Florida.mp3";
        //http://www13.zippyshare.com/v/16607190/file.html
    }

    public static String getName(String url){
        try{
        String link = parseToLink(url);
        return link.substring(link.lastIndexOf('/')+1);
        }catch(Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
